﻿using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;

namespace XamlFoundation.Globalization
{
    public class TranslateExtension : MarkupExtension, IMultiValueConverter
    {
        public TranslateExtension()
        {
        }

        public TranslateExtension(string key)
        {
            Key = key;
        }

        public string Key { get; set; }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            var xamlContext = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));
            var multiBinding = new MultiBinding();

            multiBinding.Bindings.Add(new Binding
                                      {
                                          Path = new PropertyPath(Globalization.LanguageProperty),
                                          Source = xamlContext.TargetObject,
                                      });

            multiBinding.Bindings.Add(new Binding
                                    {
                                        Path = new PropertyPath(Globalization.LocalizationProviderProperty),
                                        Source = xamlContext.TargetObject,
                                    });

            multiBinding.Converter = this;

            return multiBinding.ProvideValue(serviceProvider);
        }


        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            var language = values[0] as CultureInfo;
            var provider = values[1] as ILocalizationProvider;
            
            if (provider != null && language != null)
            {
                return provider.GetResource(Key, language);    
            }
            
            return null;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
